package com.baseframe.auth.utils;


import com.baseframe.auth.entity.UserBean;
import com.baseframe.jwt.utils.JwtUtil;
import com.baseframe.tool.container.Kv;
import com.baseframe.tool.utils.data.StringUtil;
import com.baseframe.tool.utils.web.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class AuthUtil {

    private static final String BASE_USER_BEAN = "BASE_USER_BEAN";


    /**
     * 获取当前登录用户的信息
     * @param request 当前请求
     * @return userBean 对象
     */
    public static UserBean getUserBean(HttpServletRequest request){

        Object attribute = request.getAttribute(BASE_USER_BEAN);
        if (attribute==null){
            String authHeader = request.getHeader(TokenUtil.AUTHORIZATION);
            String authParams = request.getParameter(TokenUtil.AUTHORIZATION);
            String auth = StringUtil.isBlank(authHeader)?authParams:authHeader;
            String token = TokenUtil.stripOffPrefixes(auth);
            if (StringUtil.isBlank(token)){
                return null;
            }
            UserBean userBean = TokenUtil.parse(token);
            request.setAttribute(BASE_USER_BEAN,userBean);
            return userBean;
        }

        return (UserBean) attribute;
    }

    /**
     * 获取当前登录对象
     * @return userBean 用户对象
     */
    public static UserBean getUserBean(){
        HttpServletRequest request = WebUtil.getRequest();
        return getUserBean(request);
    }

    /**
     * 获取当前用户编号
     * @return 用户编号
     */
    public static Long getUserId(){

        return getUserBean().getUserId();
    }

    /**
     * 获取当前用户名
     * @return 用户名
     */
    public static String getUsername(){
        return getUserBean().getUsername();
    }

    /**
     * 获取角色编号
     * @return 角色编号
     */

    public static Long getRoleId(){
        return getUserBean().getRoleId();
    }

    /**
     * 获取拓展信息
     * @return 拓展信息
     */
    public static Kv getDetails(){
        return getUserBean().getDetails();
    }

    /**
     * 获取当前用户权限
     * @return 用户权限
     */
    public static List<String> getAuthorities(){
        return getUserBean().getAuthorities();
    }

    /**
     * 获取客户端id
     * @return 客户端id
     */
    public static String getClientId(){
        return getUserBean().getClientId();
    }

    public static String getJwtKey(){
        HttpServletRequest request = WebUtil.getRequest();
        String headerAuth = request.getHeader(TokenUtil.AUTHORIZATION);
        String paramsAuth = request.getParameter(TokenUtil.AUTHORIZATION);
        String auth = StringUtil.isBlank(headerAuth)?paramsAuth:headerAuth;
        String token = TokenUtil.stripOffPrefixes(auth);

        return JwtUtil.getJwtId(token);
    }

}
